package com.zpark.service.impl;

import com.zpark.entity.Product;
import com.zpark.entity.Review;
import com.zpark.mapper.ProductMapper;
import com.zpark.mapper.ReviewMapper;
import com.zpark.service.IReviewService;
import com.zpark.service.ex.DeleteException;
import com.zpark.service.ex.FindProductByPidNotFoundException;
import com.zpark.service.ex.FindReviewByPidNotFoundException;
import com.zpark.service.ex.InsertException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ReviewServiceImpl implements IReviewService {

    @Autowired
    private ReviewMapper reviewMapper;

    @Autowired
    private ProductMapper productMapper;

    @Override
    public void insertReview(Integer pid, String name, String email,String sreview, Review review) {
        review.setPid(pid);
        review.setName(name);
        review.setEmail(email);
        review.setReview(sreview);
        Integer rows = reviewMapper.insertReview(review);
        if (rows != 1)
            throw new InsertException("新增数据失败请联系管理员");
    }

    @Override
    public List<Review> findReviewByPid(Integer pid) {
        List<Review> result = reviewMapper.findReviewByPid(pid);
        if (result == null){
            throw new FindReviewByPidNotFoundException("该商品没有评价");
        }
        return result;
    }

    @Override
    public void deleteReviewByPidAndRid(Integer pid, Integer rid) {
        Product product = productMapper.findById(pid);
        if (product == null){
            throw new FindProductByPidNotFoundException("没有查询到该商品信息");
        }
        List<Review> result = reviewMapper.findReviewByPid(pid);
        if (product != null && result.size() == 0){
            throw new FindReviewByPidNotFoundException("该商品中并没有被评价过");
        }
        Integer rows = reviewMapper.deleteReviewByRid(rid);
        if (rows != 1){
            throw new DeleteException("删除失败，请联系管理员");
        }
    }
}
